package com.mentaleye.biz.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mentaleye.bean.DeptBean;
import com.mentaleye.biz.DeptBiz;
import com.mentaleye.service.DeptService;
import com.mentaleye.util.CommonResult;

@Service
public class DeptBizImpl implements DeptBiz{

	@Autowired private DeptService deptService;
	
	private static Logger logger = Logger.getLogger(DeptBizImpl.class);
	
	public CommonResult editDept(DeptBean deptBean){
		CommonResult result = new CommonResult();
		boolean success = false;
		try {
			if(deptBean.getDeptId() == null){
				success = deptService.addDept(deptBean);
				if(success){
					List<DeptBean> deptlist = deptService.queryByUpDeptIdAndDeptName(deptBean.getUpDeptId(), deptBean.getDeptName());
					DeptBean updateDept = deptService.queryDeptByDeptId(deptBean.getUpDeptId());
					for (DeptBean dept : deptlist) {
						dept.setDeptUrl(updateDept.getDeptUrl()+dept.getDeptId()+";");
						deptService.modifyDept(dept);
					}
				}
			}else{
				success = deptService.modifyDept(deptBean);
			}
			result.setIsSuccess(success);
		} catch (Exception e) {
			logger.error("编辑机构异常",e);
		}
		return result;
	}
	
	public CommonResult removeDept(int deptId){
		boolean success = false;
		try {
			success = deptService.removeDept(deptId);
		} catch (Exception e) {
			logger.error("删除机构异常",e);
		}
		return new CommonResult(success);
	}
	
	public List<DeptBean> queryByExample(DeptBean deptBean){
		try {
			if(deptBean == null){
				return deptService.queryDeptAll();
			}else if(deptBean.getDeptUrl() != null){
				return deptService.queryByUrlLike(deptBean.getDeptUrl());
			}else if(deptBean.getUpDeptId() != null){
				return deptService.queryDeptByUpDeptId(deptBean.getUpDeptId());
			}
		} catch (Exception e) {
			logger.error("机构列表查询异常", e);
		}
		return null;
	}
	
	public DeptBean queryDeptByDeptId(Integer deptId){
		try {
			return deptService.queryDeptByDeptId(deptId);
		} catch (Exception e) {
			logger.error("机构信息查询异常", e);
		}
		return null;
	}
}
